package classes
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;

	public class FileHandler
	{
		// Variables
		private static var m_supportedFormats : ArrayCollection = new ArrayCollection(["flv", "f4v", "m4p", "mp4", "mp3"]);
		
		// Methods
		public static function CheckForValidFormat(a_filePath:String) : Boolean
		{
			// Get the file ending.
			var fileEnding : String = GetFileEnding(a_filePath);
			
			// Go through all the supported formats and see if the files format is actually supported.
			for (var i:int = 0; i < m_supportedFormats.length; i++)
			{
				if (fileEnding.toLowerCase() == m_supportedFormats[i])
				{
					return true;
				}
			}			
			return false;
		}
		
		public static function GetFileEnding(a_filePath:String) : String
		{
			// Split the filepath at the dots to get the file ending.
			var tempArray : Array = a_filePath.split(".");
			
			// Get the last element in the array (should contain the file ending). 
			var fileEnding : String = tempArray[tempArray.length - 1];
			
			return fileEnding;
		}
		
		public static function GetFileNameFromFilepath(a_filePath:String) : String
		{
			var fileName : String = "";
			
			// Pick out only the filename in the path.
			var parts : Array = a_filePath.split("/");
			
			// Pick replace the framework generated replacement for a whitespace with an actual whitespace.
			fileName = parts[parts.length-1];
			
			var pattern : RegExp = /(\%20)/g;
			
			fileName = fileName.replace(pattern, " ");
			
			// Remove the fileending.
			parts = fileName.split(".");
			
			fileName = parts[0];			
			
			return fileName;
		}
		
		public static function GetMediaFromFile(a_file:File) : ArrayCollection
		{
			// Create the list for the media
			var listOfMedia : ArrayCollection = new ArrayCollection();
			
			// Create the xml object that the XML should be read to.
			var myXML : XML;
			
			// Read the XML from the file.
			var fs : FileStream = new FileStream();
			fs.open(a_file, FileMode.READ);
			myXML = XML(fs.readUTFBytes(fs.bytesAvailable));			
			fs.close();
			
			// Go through the xml untill you're out of files to load.
			for (var i : int = 0; i < myXML.media.length(); i++)
			{
				var media : MediaFile = new MediaFile(myXML.media.name[i], myXML.media.url[i]);
				listOfMedia.addItem(media);
			}
			
			return listOfMedia;
		}
	}
}